/*
evsync.js

Web worker. http://www.whatwg.org/specs/web-workers/current-work/

My purpose in life is to query the evurl for new events
and sync any found to the local store.

This requires json.js - make sure you pack them together before deploying.
*/

var db = openDatabase('minerva.web.db', '1.0', 'Minerva DB', 1024*1024*5);
var timer;


onmessage = function(event) {
  var url = event.data;
  postMessage('Looking for new events ...');
  syncShareEvents(url);
  };


onerror = function(event) {
  var err = event.data;
  postMessage('ERROR: ' + err);
  };


var getResource = function(url, callback) {
  var req = new XMLHttpRequest();
  req.open('GET', url);
  req.onreadystatechange = function() {
    if (req.readyState == 4) {
      callback(req.responseText);
      }
    };
  req.send();
  };


/*
Get latest event stored to NounEvents table.
*/
var getLatestStoredEvent = function() {
  var rs = db.execute('select * from NounEvents order by created desc limit 1');
  if (rs.isValidRow()) {
    var path = rs.fieldByName('path');
    var created = rs.fieldByName('created');
    return rs;
    }
  else {
    return null;
    }
  };


var syncShareEvents = function(url, sid) {
  // If no events exist, leave unspecified
  var qstr = '';
  db.transaction(function(tx) { 
    // Get latest event stored to NounEvents table.
    tx.executeSql('select * from NounEvents order by created desc limit 1', [],
      function(tx, results) { 
        if (results.rows.length > 0) { 
          // Get last stored pwun and use that as 'from' time
          qstr = '&since=' + results.rows.item(0).pwun;
        }
        getResource(url + qstr, function(response) {
          // TODO: Check response to see if it was a failure.
          var data = JSON.parse(response);
          var events = data.events;
          db.transaction(function(tx) {
            for (var i = 0; i < events.length; i++) {
              tx.executeSql(
                'insert into NounEvents values (?, ?, ?, ?, ?, ?, ?)', events[i]
              );
            }
            if (i) {
              postMessage('Synced ' + i + ' new evs to local store.');
            }
          });

          if (data.number_remaining > 0) {
            postMessage(
              'There are ' + data.number_remaining + ' new evs left to sync ...');
            timer = setTimeout(function() {syncShareEvents(url)}, 2000);
          }
          else {
            postMessage('Local store in sync.');
          }
        });
      }, function(tx, error) { }
    );
  });
};
